<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of MyModel
 *
 * @author witoslaw.sosnowski
 */


/**
 * Model implementing SQLite vendor specific database extension.
 */
abstract class MyModel extends _Model
{
    private static $count = 0;

    function __construct()
    {
        ++self::$count;
        if (empty(self::$db) && !empty(self::$dsn) && preg_match('/[:;]host=([^;]+)/i', self::$dsn, $matches))
        {
            self::$db = @ mysql_connect($matches[1], self::$user, self::$password);
            if (!self::$db) throw new Exception(mysql_error(), mysql_errno());
            if (preg_match('/[:;]dbname=([^;]+)/i', self::$dsn, $matches) && @ !mysql_select_db($matches[1], self::$db)) throw new Exception(mysql_error(self::$db), mysql_errno(self::$db));
        }
    }

    protected function execute($name, $arguments=array())
    {
        if (!array_key_exists($name, $this->sql)) throw new Exception('Execute of undefined sql ' . $name);
        $sql = $this->sql[$name];
        foreach ($arguments as $key => $value)
        {
            foreach ($arguments as $key => $value)
            {
                switch (gettype($value))
                {
                    case 'boolean':
                        $value = $value ? 1 : 0;
                        break;
                    case 'integer':
                    case 'double':
                        break;
                    case 'NULL':
                        $value = 'NULL';
                        break;
                    default:
                        $value = "'" . addslashes($value) . "'";
                }
            }
            $sql = preg_replace('/:' . preg_quote($key, '/') . '([^0-9a-z_]|$)/i', $value . '$1', $sql);
        }
        $resource = @ mysql_query($sql, self::$db);
        if (!$resource) throw new Exception(mysql_error(self::$db), mysql_errno(self::$db));
        $result = array();
        if (preg_match('/^[^A-Z_]*SELECT[^A-Z_]/i', $this->sql[$name]))
        {
            while (($object = $this->className ? mysql_fetch_object($resource, $this->className) : mysql_fetch_object($resource))) $result[] = $object;
        }
        else
        {
            $object = (object)array('count' => mysql_affected_rows($resource));
            if (preg_match('/^[^A-Z_]*(INSERT|REPLACE)[^A-Z_]/i', $this->sql[$name])) $object->id = mysql_insert_id($resource);
            $result[] = $object;
        }
        return $result;
    }

    function __destruct()
    {
        --self::$count;
        if (!empty(self::$db) && self::$count <= 0)
        {
            if (@ !mysql_close(self::$db)) throw new Exception(mysql_error(self::$db), mysql_errno(self::$db));
            self::$db = null;
        }
    }
}
?>